<?php

namespace app\model\agency;

use app\base\BaseModel;
use app\model\goods\GoodsModel;
use app\model\goods\GoodsStoreModel;
use think\model\concern\SoftDelete;

/**
 * 模型-AgentGoodsModel
 * Class AgentGoodsModel
 * @package app\model
 */
class AgencyGoodsModel extends BaseModel
{
    use SoftDelete;
    protected $name = 'agency_goods';

    public function getPageAgencyList($map, $mapLike, $order, $current_page, $list_rows, $field = 'a.*,g.goods_title,g.goods_img,g.goods_sale as goods_system_sale,g.goods_bazaar_price')
    {
        $model = $this;
        $model = $model->alias("a")->leftJoin("t_goods g", "a.goods_id=g.id")->field($field);
        if (!empty($mapLike)) {
            foreach ($mapLike as $key => $value) {
                $model = $model->whereLike($key, $value, "OR");
            }
        }
        foreach ($map as $k => $v) {
            $model = $model->where($k, $v);
        }
        $dataList = $model
            ->order($order)
            ->paginate(['page' => $current_page, 'list_rows' => $list_rows], false);
        $current = $dataList->currentPage();
        $total = $dataList->total();
        $limit = $dataList->listRows();
        $ret = ['total' => $total, 'current' => $current, 'limit' => $limit, 'dataList' => $dataList->items()];
        return $ret;
    }

    /**
     * 商品库存变化
     * @param $storage
     * @param $change
     * @param int $admin_id
     * @param int $user_id
     * @param bool $is_buy
     * @return AgencyGoodsModel|bool|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changeStore($storage, $change, $admin_id = 0, $user_id = 0, $is_buy = false)
    {
        $map = ['agency_id' => $storage['target_id'], 'goods_id' => $storage['goods_id'], 'attribute_ids' => $storage['attribute_ids']];
        if ($is_buy) {
            $goods_data = $this->where($map)->where('goods_storage', '>', 0)->find();
            if (empty($goods_data)) {
                return 0;
            }
        } else {
            $goods_data = $this->where($map)->find();
            if (empty($goods_data)) {
                if ($change == 'add') {
                    $goods_in = [
                        'agency_id' => $storage['target_id'],
                        'attribute_ids' => $storage['attribute_ids'],
                        'goods_id' => $storage['goods_id'],
                        'goods_storage' => $storage['storage'],
                        'admin_id' => $admin_id,
                        'remark' => $storage['remark']
                    ];
                    return $this->addGoods($goods_in);
                } else {
                    return false;
                }
            }
        }
        $this->startTrans();
        if ($change == 'add') {
            $up_data = [
                'goods_storage' => $storage['storage'] + intval($goods_data['goods_storage'])
            ];
        } else {
            if ((intval($goods_data['goods_storage']) - $storage['storage']) < 0) {
                if ($is_buy) {
                    $this->commit();
                    return (intval($storage['storage']) - intval($goods_data['goods_storage']));
                }
                $this->rollback();
                return false;
            }
            $up_data = [
                'goods_storage' => intval($goods_data['goods_storage']) - $storage['storage'],
            ];
            if (!empty($user_id)) {
                $storage['remark'] = "代理商售卖";
                $goods_model = new GoodsModel();
                $goods_data_temp = $goods_model->where(['id' => $storage['goods_id']])->field('goods_sale')->find();
                $up_goods_data = [
                    'goods_sale' => intval($goods_data_temp['goods_sale']) + intval($storage['storage'])
                ];
                $goods_model->where(['id' => $storage['goods_id']])->update($up_goods_data);
            }
        }
        $ret = $this->where($map)->update($up_data);
        if ($ret !== false) {
            $in_data = [
                'goods_id' => $storage['goods_id'],
                'attribute_ids' => $storage['attribute_ids'],
                'last_storage' => $goods_data['goods_storage'],
                'storage' => $storage['storage'],
                'change' => $change,
                'user_id' => $user_id,
                'target_id' => $storage['target_id'],
                'operate' => 'agency',
                'admin_id' => $admin_id,
                'remark' => $storage['remark'],
                'add_time' => time()
            ];
            $goods_store_model = new GoodsStoreModel();
            $ret = $goods_store_model->addStorage($in_data);
            if ($ret !== false) {
                $this->commit();
                return $ret;
            }
        }
        $this->rollback();
        return false;
    }


    /**
     * 添加代理商商品
     * @param array $goods
     * $goods['goods_storage'] 变化库存
     * $goods['admin_id'] 管理员id
     * @return bool
     * @throws \Exception
     */
    public function addGoods($goods = [])
    {
        $goods_id = $goods['goods_id'];
        $ret = false;
        if (strpos($goods_id, ',') !== false) {
            $goods_ids = explode(',', $goods_id);
            foreach ($goods_ids as $value) {
                $goods['goods_id'] = $value;
                $ret = $this->_addGoods($goods);
            }
        } else {
            $ret = $this->_addGoods($goods);
        }
        return $ret;
    }

    /**
     * 添加单个商品
     * @param $goods
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    private function _addGoods($goods)
    {
        $map = [
            'agency_id' => $goods['agency_id'],
            'goods_id' => $goods['goods_id']
        ];
        $goods_storage = $goods['goods_storage'];
        $admin_id = $goods['admin_id'];
        unset($goods['goods_storage']);
        unset($goods['admin_id']);
        $this->withTrashed = true;
        $temp_goods = $this->where($map)->find();
        if (empty($temp_goods)) {
            $ret = $this->saveData($goods);
            if ($ret === false) {
                throw new \think\Exception("商品添加失败", 0);
            } else {
                $m_ret = true;
            }
        } else {
            $delete_time = $temp_goods['delete_time'];
            if (!empty($delete_time)) {
                $goods['delete_time'] = 0;
                $ret = $this->where('id', $temp_goods['id'])->update($goods);
                if ($ret === false) {
                    return false;
                } else {
                    $m_ret = true;
                }
            } else {
                return false;
            }
        }
        if ($m_ret) {
            $goods_model = new GoodsModel();
            $storage = [
                'storage' => $goods_storage,
                'attribute_ids' => $goods['attribute_ids'],
                'target_id' => $goods['agency_id'],
            ];
            $operate = [
                'operate' => 'agency',
                'admin_id' => $admin_id
            ];
            $remark = '代理商添加商品';
            if (!empty($goods['remark'])) {
                $remark = $goods['remark'];
            }
            $ret = $goods_model->changeStore($goods['goods_id'], $storage, 'add', 0, $operate, $remark);
            if ($ret === true) {
                return true;
            }
        }
        return false;
    }

    /**
     * 删除代理商商品
     * @param $id
     * @param $admin_id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delGoods($id, $admin_id)
    {

        $goods_temp = $this->where('id', $id)->find();
        if (empty($goods_temp)) {
            return false;
        }
        $goods_storage = $goods_temp['goods_storage'];
        $goods_id = $goods_temp['goods_id'];
        $agency_id = $goods_temp['agency_id'];
        $goods_model = new GoodsModel();
        $storage = [
            'storage' => $goods_storage,
            'target_id' => $agency_id
        ];
        $operate = [
            'operate' => 'agency',
            'admin_id' => $admin_id
        ];
        if (intval($goods_storage) > 0) {
            $ret = $goods_model->changeStore($goods_id, $storage, 'sub', 0, $operate, '代理商退还商品');
            if ($ret === true) {
                $this::destroy(['id' => $id]);
                return true;
            }
        } else {
            $this::destroy(['id' => $id]);
            return true;
        }
        return false;
    }

    /**
     * 代理商商品总库存
     * @param $agency_id
     * @return int
     */
    public function countStore($agency_id)
    {
        $goods_storage = $this->where(['agency_id' => $agency_id])->sum('goods_storage');
        if (empty($goods_storage)) {
            $goods_storage = 0;
        }
        return $goods_storage;
    }

    /**
     * 代理商商品总类型数量
     * @param $agency_id
     * @return int
     */
    public function countGoods($agency_id)
    {
        $goods_count = $this->where(['agency_id' => $agency_id])->count();
        if (empty($goods_count)) {
            $goods_count = 0;
        }
        return $goods_count;
    }


    /**
     * 普通商品项处理
     * @param string $goods_ids
     * @param string $goods_number
     * @param string $channel
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getGoodsItem($goods_ids = '', $goods_number = '', $channel = '')
    {
        $goods_model = new GoodsModel();
        $field = 'id,goods_original_price,goods_freight,goods_agency_price,goods_return_agency_money,goods_return_money,goods_top_money,goods_storage,goods_title,goods_img';
        if (strpos($goods_ids, ',') > 0) {
            $goods_number_arr = [];
            if (!empty($goods_number)) {
                $goods_number = explode(',', $goods_number);
                foreach (explode(',', $goods_ids) as $key => $v) {
                    $goods_number_arr[intval($v)] = $goods_number[$key];
                }
            } else {
                foreach (explode(',', $goods_ids) as $key => $v) {
                    $goods_number_arr[intval($v)] = 1;
                }
            }
            $goods_list = $goods_model->getGoodsIdIn($goods_ids, $field);
            if (empty($goods_list)) {
                $rsps['code'] = 0;
                $rsps['msg'] = "商品不存在";
                return $rsps;
            }
            $goods_data = [];
            $total = 0;
            $keyword = "";
            foreach ($goods_list as $value) {
                if (intval($goods_number_arr[intval($value['id'])]) > intval($value['goods_storage'])) {
                    $rsps['code'] = 0;
                    $rsps['data'] = $value['id'];
                    $rsps['msg'] = "商品库存不足";
                    return $rsps;
                }
                $goods_data[] = [
                    'goods_id' => $value['id'],
                    'goods_title' => $value['goods_title'],
                    'goods_img' => $value['goods_img'],
                    'platform_price' => $value['goods_original_price'],
                    'goods_price' => $value['goods_original_price'],
                    'goods_agency_price' => $value['goods_agency_price'],
                    'goods_freight' => $value['goods_freight'],
                    'agency_money' => $value['goods_return_agency_money'],
                    'return_money' => $value['goods_return_money'],
                    'agency_profit_money' => floatval($value['goods_original_price']) - floatval($value['goods_agency_price']),
                    'top_money' => $value['goods_top_money'],
                    'goods_storage' => $value['goods_storage'],
                    'goods_number' => $goods_number_arr[intval($value['id'])],
                    'channel' => $channel
                ];
                $total += (floatval($value['goods_agency_price']) * $goods_number_arr[intval($value['id'])]);
                $keyword .= $value['goods_title'] . "|";
            }
            $rsps['code'] = 1;
            $rsps['data'] = $goods_data;
            $rsps['total'] = $total;
            $rsps['keyword'] = $keyword;
            $rsps['msg'] = "获取成功";
            return $rsps;
        } else {
            $goods = $goods_model->getInfo($goods_ids, $field);
            if (empty($goods)) {
                $rsps['code'] = 0;
                $rsps['msg'] = "商品不存在";
                return $rsps;
            }
            if (empty($goods_number)) {
                $goods_number = 1;
            }
            if (intval($goods_number) > intval($goods['goods_storage'])) {
                $rsps['code'] = 0;
                $rsps['data'] = $goods['id'];
                $rsps['msg'] = "商品库存不足";
                return $rsps;
            }
            $goods_data[] = [
                'goods_id' => $goods['id'],
                'goods_title' => $goods['goods_title'],
                'goods_img' => $goods['goods_img'],
                'platform_price' => $goods['goods_original_price'],
                'goods_price' => $goods['goods_original_price'],
                'goods_freight' => $goods['goods_freight'],
                'goods_agency_price' => $goods['goods_agency_price'],
                'agency_money' => $goods['goods_return_agency_money'],
                'return_money' => $goods['goods_return_money'],
                'agency_profit_money' => floatval($goods['goods_original_price']) - floatval($goods['goods_agency_price']),
                'top_money' => $goods['goods_top_money'],
                'goods_storage' => $goods['goods_storage'],
                'goods_number' => $goods_number,
                'channel' => $channel
            ];
            $total = (floatval($goods['goods_agency_price']) * intval($goods_number));
            $keyword = $goods['goods_title'];
            $rsps['code'] = 1;
            $rsps['data'] = $goods_data;
            $rsps['keyword'] = $keyword;
            $rsps['total'] = $total;
            $rsps['msg'] = "获取成功";
            return $rsps;
        }
    }

    /**
     * 获取代理商制定商品库存
     * @param $agency_id
     * @param $goods_id
     * @param $attribute_ids
     * @return int|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getStore($agency_id, $goods_id = '', $attribute_ids = '')
    {
        if (empty($agency_id)) {
            return 0;
        }
        $map = [
            'agency_id' => $agency_id,
            'goods_id' => $goods_id
        ];
        if (!empty($attribute_ids)) {
            $map['attribute_ids'] = $attribute_ids;
        }
        $data = self::where($map)->field('goods_storage')->find();
        if (empty($data)) {
            return 0;
        }
        return $data['goods_storage'];
    }
}
